<?php

class Rzd_Validate_PhotosDynamic extends Zend_Validate_Abstract
{
    const COMMENT_REQUIRED_WITH_FILE = 'CommentRequiredWithFile';

    protected $_fieldName;
    protected $_validateOptions;

    protected $_messageTemplates = array(
        self::COMMENT_REQUIRED_WITH_FILE => "One file is empty, but it has not empty comment",
    );

    public function __construct($fieldName, $validateOptions)
    {
        $this->_fieldName = $fieldName;
        $this->_validateOptions = $validateOptions;
    }


    public function isValid($value)
    {
        $fileSizeValidator = new Zend_Validate_File_FilesSize($this->_validateOptions['filesize']);
        $extensionValidator = new Zend_Validate_File_Extension($this->_validateOptions['extension']);

        foreach($value as $index => $fileInfo) {

            if(empty($_FILES[$this->_fieldName]['name'][$index])) {
                if((!empty($fileInfo['comment'])) && (!isset($fileInfo['id']))) {
                    $this->_error(self::COMMENT_REQUIRED_WITH_FILE);
                    return false;
                }
            } else {
                $uploadFile = $_FILES[$this->_fieldName]['tmp_name'][$index];

                $isValid = true;
                if(!$fileSizeValidator->isValid($uploadFile)) {
                    $this->_putErrorsFromOtherValidator($fileSizeValidator);
                    $isValid = false;
                }

                $fileParams = array(
                    'name' => $_FILES[$this->_fieldName]['name'][$index]
                );

                if(!$extensionValidator->isValid($uploadFile, $fileParams)) {
                    $this->_putErrorsFromOtherValidator($extensionValidator);
                    $isValid = false;
                }

                if(!$isValid) {
                    return false;
                }
            }
        }

        return true;
    }

    public function _putErrorsFromOtherValidator($validator)
    {
        $errors = $validator->getErrors();
        $messages = $validator->getMessages();

        foreach ($errors as $messageKey) {
            $this->_ownError($messageKey, $messages[$messageKey]);
        }
    }

    public function _ownError($messageKey, $message)
    {
        $this->_errors[] = $messageKey;
        $this->_messages[$messageKey] = $message;
    }
}
